package com.online.onlinestudent.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.online.onlinestudent.dto.AjaxResult;
import com.online.onlinestudent.entity.Comment;
import com.online.onlinestudent.entity.Course;
import com.online.onlinestudent.entity.Student;
import com.online.onlinestudent.service.CommentService;
import com.online.onlinestudent.service.CourseService;
import com.online.onlinestudent.service.StudentService;
import com.online.onlinestudent.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private CourseService courseService;

    @GetMapping
    public AjaxResult getAllComments() {
        List<Comment> comments = commentService.list();
        if (comments == null || comments.isEmpty()) {
            return AjaxResult.fail("未查询到结果！");
        }
        return AjaxResult.success(comments);
    }

    @GetMapping("/{id}")
    public AjaxResult getCommentById(@PathVariable Long id) {
        Comment comment = commentService.getById(id);
        if (comment != null) {
            return AjaxResult.success(comment);
        } else {
            return AjaxResult.fail("不存在该评论！");
        }
    }

    @PostMapping
    public AjaxResult saveComment(@RequestBody Comment comment) {
        try {
            boolean saved = commentService.save(comment);
            if (saved) {
                return AjaxResult.success("插入成功！");
            } else {
                return AjaxResult.fail("插入失败！");
            }
        } catch (Exception e) {
            return AjaxResult.fail("插入失败：" + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public AjaxResult updateComment(@PathVariable Long id, @RequestBody Comment comment) {
        comment.setId(id);
        try {
            boolean updated = commentService.updateById(comment);
            if (updated) {
                return AjaxResult.success("更新成功！");
            } else {
                return AjaxResult.fail("更新失败，请重新输入！");
            }
        } catch (Exception e) {
            return AjaxResult.fail("更新失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteCommentById(@PathVariable Long id) {
        try {
            boolean deleted = commentService.removeById(id);
            if (deleted) {
                return AjaxResult.success("删除成功！");
            } else {
                return AjaxResult.fail("删除失败，不存在该评论！");
            }
        } catch (Exception e) {
            return AjaxResult.fail("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/page")
    public AjaxResult getCommentsByPage(@RequestParam int current, @RequestParam int size) {
        try {
            Page<Comment> page = commentService.page(new Page<>(current, size));
            if (page == null || page.getRecords().isEmpty()) {
                return AjaxResult.fail("未查询到结果！");
            }
            return AjaxResult.success(page);
        } catch (Exception e) {
            return AjaxResult.fail("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/page/courseId")
    public AjaxResult getCourseCommentsByPage(@RequestParam int current, @RequestParam int size, @RequestParam Long courseId) {
        try {
            String courseName = courseService.getById(courseId).getTitle();
            // 获取评论列表
            List<Comment> comments = commentService.getCommentsByCourseId(courseId);
            if (comments == null || comments.isEmpty()) {
                return AjaxResult.fail("未查询到结果！");
            }

            // 创建分页对象
            Page<CommentVO> page = new Page<>(current, size);
            List<CommentVO> commentVOs = new ArrayList<>();

            // 将 Comment 转换为 CommentVO
            for (Comment comment : comments) {
                Long studentId = comment.getStudentId();
                Student student = studentService.getById(studentId);
                CommentVO commentVO = new CommentVO();
                commentVO.setCourseId(comment.getCourseId());
                commentVO.setContent(comment.getContent());
                commentVO.setCreatedAt(comment.getCreatedAt());
                commentVO.setEmail(student.getEmail());
                commentVO.setId(comment.getId());
                commentVO.setStudentId(comment.getStudentId());
                commentVO.setStudentName(student.getUsername());
                commentVO.setCourseName(courseName);
                commentVOs.add(commentVO);
            }

            // 对 commentVOs 进行分页处理
            int total = commentVOs.size();
            int start = (int) ((current - 1) * size);
            int end = Math.min(start + size, total);
            List<CommentVO> pageList = commentVOs.subList(start, end);

            page.setTotal(total);
            page.setRecords(pageList);

            return AjaxResult.success(page);
        } catch (Exception e) {
            return AjaxResult.fail("查询失败：" + e.getMessage());
        }
    }


    @GetMapping("/courses/{id}")
    public AjaxResult getCommentsAndStudentsByCourseId(@PathVariable Long id) {
        try {
            String courseName = courseService.getById(id).getTitle();
            List<Comment> comments = commentService.getCommentsByCourseId(id);
            List<CommentVO> commentVOs = new ArrayList<>();
            if (comments == null || comments.isEmpty())
                return AjaxResult.fail("未查询到结果！");

                for (Comment comment : comments) {
                    Long studentId = comment.getStudentId();


                    Student student = studentService.getById(studentId);
                    CommentVO commentVO = new CommentVO();
                    commentVO.setCourseId(comment.getCourseId());
                    commentVO.setContent(comment.getContent());
                    commentVO.setCreatedAt(comment.getCreatedAt());
                    commentVO.setEmail(student.getEmail());
                    commentVO.setId(comment.getId());
                    commentVO.setStudentId(comment.getStudentId());
                    commentVO.setStudentName(student.getUsername());
                    commentVO.setCourseName(courseName);

                    commentVOs.add(commentVO);


            }
                return AjaxResult.success(commentVOs);

        } catch (Exception e) {
            return AjaxResult.fail("查询失败：" + e.getMessage());
        }


        }

    @GetMapping("/courses")
    public AjaxResult getAllCommentsWithCourseNameAndStudentName() {
        try {
            List<Course> courses = courseService.list();
            List<CommentVO> commentVOs = new ArrayList<>();
            for(Course course:courses){
                Long id = course.getId();
                String courseName = courseService.getById(id).getTitle();
                List<Comment> comments = commentService.getCommentsByCourseId(id);



                for (Comment comment : comments) {
                    Long studentId = comment.getStudentId();

                    Student student = studentService.getById(studentId);
                    CommentVO commentVO = new CommentVO();
                    commentVO.setCourseId(comment.getCourseId());
                    commentVO.setContent(comment.getContent());
                    commentVO.setCreatedAt(comment.getCreatedAt());
                    commentVO.setEmail(student.getEmail());
                    commentVO.setId(comment.getId());
                    commentVO.setStudentId(comment.getStudentId());
                    commentVO.setStudentName(student.getUsername());
                    commentVO.setCourseName(courseName);

                    commentVOs.add(commentVO);


                }


            }
            return AjaxResult.success(commentVOs);
        } catch (Exception e) {
            return AjaxResult.fail("查询失败：" + e.getMessage());
        }



    }





}

